'''

Case Type： 数据库系统
Case Name： 一个备节点挂掉，查看集群其他节点是否一致
Create At:  2020/07/25
@zou_jialiang0505328126
Descption:  1.创建TPCC仓库2.在执行TPCC过程中停止一个备节点进程3.TPCC执行结束后查询主备数据是否一致列出tpcc用户下所有表

history：
created： 2020/07/25  created by @wan005
'''
import os
import unittest
from yat.test import Node
import time
from yat.test import macro
import sys

sys.path.append(sys.path[0] + "/../")
from testcase.utils.Logger import Logger
from testcase.utils.Constant import Constant
from testcase.utils.Common import Common
from testcase.utils.CommonSH import *

logger = Logger()
common = Common()
commonshpri = CommonSH('PrimaryDbUser')
commonshsta1 = CommonSH('Standby1DbUser')
commonshsta2 = CommonSH('Standby2DbUser')


class KillStandbyPid(unittest.TestCase):
    dbPrimaryUserNode = Node(node='PrimaryDbUser')
    dbPrimaryRootNode = Node(node='PrimaryRoot')
    dbStandby1UserNode = Node(node='Standby1DbUser')
    dbStandby2UserNode = Node(node='Standby2DbUser')
    dbStandby1RootNode = Node(node='Standby1Root')
    DB_INSTANCE_PATH = macro.DB_INSTANCE_PATH
    DB_ENV_PATH = macro.DB_ENV_PATH
    TPCC_PATH = macro.TPCC_PATH
    RESTART_SUCCESS_MSG = Constant.RESTART_SUCCESS_MSG
    STANDBY_NORMAL = Constant.STANDBY_NORMAL
    PRIMARY_NORMAL = Constant.PRIMARY_NORMAL
    TPCC_CREATE_DATA_SUCCESS_MSG = Constant.TPCC_CREATE_DATA_SUCCESS_MSG
    nodes_tuple = ('PrimaryDbUser', 'Standby1DbUser', 'Standby2DbUser')

    @RestartDbCluster(*nodes_tuple)
    def setUp(self):
        logger.info("-----------this is setup-----------")
        logger.info('------------Opengauss_Reliability_Dbsys_Case132.py start------------')

    def test_kill_standby_node(self):
        logger.info("-----------create tpcc data-----------")
        destroy_shell = ". runDatabaseDestroy.sh props.pg"
        destroy_result = common.startTPCC(self.dbPrimaryRootNode, self.TPCC_PATH, destroy_shell)
        logger.info(destroy_result)

        build_shell = ". runDatabaseBuild.sh props.pg"
        destroy_result = common.startTPCC(self.dbPrimaryRootNode, self.TPCC_PATH, build_shell)
        logger.info(destroy_result)
        self.assertTrue(destroy_result.find(self.TPCC_CREATE_DATA_SUCCESS_MSG) > -1)

        logger.info("-----------kill standby1 pid-----------")
        getPidCmd = 'lsof -i:{port}'.replace('{port}', self.dbStandby1RootNode.db_port)
        pidMsg = self.dbStandby1RootNode.sh(getPidCmd).result()
        pid = common.getPidFromCmd(str(pidMsg))
        self.dbStandby1RootNode.sh('kill -STOP ' + pid)

        logger.info("-----------check opengauss status-----------")
        checkCmd = '''
            source {source_path};
            gs_om -t status --detail'''.format(source_path=self.DB_ENV_PATH)
        checktMsg = self.dbPrimaryUserNode.sh(checkCmd).result()
        logger.info(checktMsg)
        self.assertTrue(checktMsg.find(self.STANDBY_NORMAL) > -1)
        self.assertTrue(checktMsg.find(self.PRIMARY_NORMAL) > -1)

        # 校验备机是否完成数据同步
        logger.info('校验备机是否完成数据同步')
        flag = commonshsta2.check_data_consistency()
        self.assertTrue(flag)

        logger.info("-----------check data consistency-----------")
        nodes_tuple = (self.dbPrimaryUserNode, self.dbStandby2UserNode)
        flag = common.check_data_sample_by_all(r'\d', *nodes_tuple)
        self.assertTrue(flag)

        table_dict = common.format_sql_result(commonshpri.executDbSql(r'\d'))
        table_name = table_dict.get('Name')
        for name in table_name:
            select_sql = f'select count(*) from {name};'
            flag = common.check_data_sample_by_all(select_sql, *nodes_tuple)
            self.assertTrue(flag)

    def tearDown(self):
        logger.info('----------------this is tearDown-----------------------')
        logger.info("-----------restart opengauss-----------")

        logger.info("-----------continue standby1 pid-----------")
        getPidCmd = 'lsof -i:{port}'.replace('{port}', self.dbStandby1RootNode.db_port)
        pidMsg = self.dbStandby1RootNode.sh(getPidCmd).result()
        pid = common.getPidFromCmd(str(pidMsg))
        self.dbStandby1RootNode.sh('kill -18 ' + pid)

        restartCmd = '''
            source {source_path};
            gs_ctl restart -D {DN1_PATH} -m immediate'''.format(source_path=self.DB_ENV_PATH,
                                                                DN1_PATH=self.DB_INSTANCE_PATH)
        restartMsg = self.dbPrimaryUserNode.sh(restartCmd).result()
        logger.info(restartMsg)
        time.sleep(5)
